<?php
namespace Client;
// require 'vendor/autoload.php'; // 引入Composer自动加载文件
require_once 'pkg/credentials/credentials.php';
use Credentials\credentials;
use GuzzleHttp\Exception\RequestException;

class Config {
    public $endpoint;
    public $accessKey;
    public $secretKey;
    public $protocol = 'HTTPS';
    public $method = 'POST';

    public function __construct($endpoint, $accessKey, $secretKey, $protocol = 'HTTPS', $method = 'POST') {
        $this->endpoint = $endpoint;
        $this->accessKey = $accessKey;
        $this->secretKey = $secretKey;
        $this->protocol = $protocol;
        $this->method = $method;
    }
}

class CTAPIrequest {
    public $url;
    public $method;
    public $headers;
    public $data;
    public $query;

    public function __construct($url, $method = 'POST', $headers = [], $data = [], $query = []) {
        $this->url = $url;
        $this->method = $method;
        $this->headers = $headers;
        $this->data = $data;
        $this->query = $query;
    }
}

class SDKClient {
    public $endpoint;
    public $accessKey;
    public $secretKey;
    public $protocol;
    public $method;

    public function __construct(Config $config) {
        if (!$config->endpoint) {
            throw new \InvalidArgumentException('endpoint is required');
        }
        if (!$config->accessKey || !$config->secretKey) {
            throw new \InvalidArgumentException('aksk is required');
        }

        $this->endpoint = $config->endpoint;
        $this->accessKey = $config->accessKey;
        $this->secretKey = $config->secretKey;
        $this->protocol = $config->protocol ?? 'HTTPS';
        $this->method = $config->method ?? 'POST';
        // $this->httpClient = new HttpClient();
    }

    


    public function doRequest($requestConfig) {
        try {
            // 构建CTAPIrequest对象
            $url = sprintf('%s://%s%s', $this->protocol, $this->endpoint, $requestConfig['url']);
            $method = $this->method;
            $headers = $requestConfig['headers'];
            $data = $requestConfig['data'];
            $query = $requestConfig['query'];
            $CTAPIrequest = new CTAPIrequest($url, $method, $headers, $data, $query);


            $cre = new credentials($this->accessKey, $this->secretKey);
            $Response = $cre->doCTAPIRequest($CTAPIrequest);
            printf("Client doRequest has response with: %s\n", $Response);
            return $Response;
        } catch (RequestException $e) {
            $error = [
                'message' => $e->getMessage(),
            ];
            return $error;
        }
    }
}
